package com.ws.universal.tools.takephoto.multipleimageselect.activities;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import com.gyf.barlibrary.ImmersionBar;
import com.ws.universal.tools.R;
import com.ws.universal.tools.RequestCode;
import com.ws.universal.tools.pictureselect.manage.CollectionManage;
import com.ws.universal.tools.pictureselect.media.MediaFile;
import com.ws.universal.tools.pictureselect.task.LoadAllTask;
import com.ws.universal.tools.pictureselect.task.LoadImageTask;
import com.ws.universal.tools.pictureselect.task.MediaCallBack;
import com.ws.universal.tools.takephoto.multipleimageselect.adapters.CustomAlbumSelectAdapter;
import com.ws.universal.tools.takephoto.multipleimageselect.helpers.ConstantsCode;
import com.ws.universal.tools.takephoto.multipleimageselect.models.Album;

import java.io.File;
import java.util.ArrayList;
import java.util.HashSet;

/**
 * @author:ws
 * @date: 2020/9/1 11:57
 * @desc 相册选则
 */
public class AlbumSelectActivity extends AppCompatActivity {
    private final String TAG = AlbumSelectActivity.class.getName();
    private final String[] requiredPermissions = new String[]{Manifest.permission.READ_EXTERNAL_STORAGE};
    private ArrayList<Album> albums;
    private GridView gridView;
    private CustomAlbumSelectAdapter adapter;
    private TextView title_text_tv;
    private ProgressBar progressBar;
    private Handler handler;

    private boolean showVideo;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //沉浸式
        ImmersionBar.with(this).statusBarDarkFont(true).init();
        setContentView(R.layout.activity_album_select);


        title_text_tv = findViewById(R.id.title_text_tv);
        title_text_tv.setText(getResources().getString(R.string.album_view));
        findViewById(R.id.title_left_btn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        Intent intent = getIntent();
        if (intent == null) {
            finish();
        }
        if (albums == null) {
            albums = new ArrayList<>();
        }
        showVideo = intent.getBooleanExtra(ConstantsCode.showVideo, false);
        ConstantsCode.limit = intent.getIntExtra(ConstantsCode.INTENT_EXTRA_LIMIT, ConstantsCode.DEFAULT_LIMIT);

        gridView = (GridView) findViewById(R.id.grid_view_album_select);
        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(getApplicationContext(), ImageSelectActivity.class);
                intent.putExtra(ConstantsCode.INTENT_EXTRA_ALBUM, albums.get(position).name);
                intent.putExtra(ConstantsCode.showVideo, showVideo);
                startActivityForResult(intent, RequestCode.RequestCode_Photo);
            }
        });
        progressBar = findViewById(R.id.progress_bar_album_select);

        initData();
    }

    @Override
    protected void onStart() {
        super.onStart();
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case ConstantsCode.PERMISSION_DENIED: {


                        progressBar.setVisibility(View.INVISIBLE);
                        gridView.setVisibility(View.INVISIBLE);

                        break;
                    }

                    case ConstantsCode.FETCH_STARTED: {
                        progressBar.setVisibility(View.VISIBLE);
                        gridView.setVisibility(View.INVISIBLE);

                        break;
                    }
                    case ConstantsCode.FETCH_COMPLETED: {
                        if (adapter == null) {
                            adapter = new CustomAlbumSelectAdapter(getApplicationContext(), albums);
                            gridView.setAdapter(adapter);
                            progressBar.setVisibility(View.INVISIBLE);
                            gridView.setVisibility(View.VISIBLE);
                            orientationBasedUI(getResources().getConfiguration().orientation);
                        } else {
                            adapter.notifyDataSetChanged();
                        }
                        break;
                    }
                    case ConstantsCode.ERROR: {
                        progressBar.setVisibility(View.INVISIBLE);
                        break;
                    }
                }
            }
        };
    }

    @Override
    protected void onStop() {
        super.onStop();

        if (handler != null) {
            handler.removeCallbacksAndMessages(null);
            handler = null;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        albums = null;
        if (adapter != null) {
            adapter.releaseResources();
        }
        gridView.setOnItemClickListener(null);
    }

    private void orientationBasedUI(int orientation) {
        final WindowManager windowManager = (WindowManager) getApplicationContext().getSystemService(Context.WINDOW_SERVICE);
        final DisplayMetrics metrics = new DisplayMetrics();
        windowManager.getDefaultDisplay().getMetrics(metrics);

        if (adapter != null) {
            int size = orientation == Configuration.ORIENTATION_PORTRAIT ? metrics.widthPixels / 2 : metrics.widthPixels / 4;
            adapter.setLayoutParams(size);
        }
        gridView.setNumColumns(orientation == Configuration.ORIENTATION_PORTRAIT ? 2 : 4);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        setResult(RESULT_CANCELED);
        finish();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == RequestCode.RequestCode_Photo && data != null) {
            setResult(RequestCode.RequestCode_Photo, data);
            finish();
        }
    }


    /**
     * 获取数据
     */
    private void initData() {

        Runnable runnableTask = null;

        if (!showVideo) {//只加载图片
            //
            runnableTask = new LoadImageTask(this, new CallBackData());
            //        } else if (showVideo && !showImage) {//只加载视频
            //            runnableTask = new LoadVideoTask(this, new CallBackData());

        } else if (runnableTask == null) {//全部加载
            runnableTask = new LoadAllTask(this, new CallBackData());
        }
        new Thread(runnableTask).start();
    }

    /**
     * 返回数据的接口
     */
    class CallBackData implements MediaCallBack {

        @Override
        public void resultArrayList(final ArrayList<MediaFile> list) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Message message;
                    if (adapter == null) {
                        message = handler.obtainMessage();
                        message.what = ConstantsCode.FETCH_STARTED;
                        message.sendToTarget();
                    }
                    if (Thread.interrupted()) {
                        return;
                    }
                    CollectionManage.getInstance().setAllList(list);

                    ArrayList<Album> temp = new ArrayList<>();
                    HashSet<String> albumSet = new HashSet<>();
                    File file;
                    for (int i = 0; i < list.size(); i++) {
                        String album = list.get(i).getFolderName();
                        String image = list.get(i).getPath();
                        String type = list.get(i).getMime();
                        file = new File(list.get(i).getPath());
                        if (file.exists() && !albumSet.contains(album)) {
                            temp.add(new Album(album, image, type));
                            albumSet.add(album);
                        }
                    }
                    albums.clear();
                    albums.addAll(temp);
                    message = handler.obtainMessage();
                    message.what = ConstantsCode.FETCH_COMPLETED;
                    message.sendToTarget();
                }
            });

        }
    }


}
